<template>
  <div>
    <p>Received: {{ message }}</p>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue';

let ws;
let isConnected = false;  // 用于标记是否已连接

const message = ref('');

function connect() {
  if (isConnected) {  // 如果已连接，直接返回
    return;
  }
  ws = new WebSocket('ws://localhost:8888');

  ws.onmessage = (event) => {
    message.value = event.data;
  };

  ws.onopen = () => {
    isConnected = true;  // 标记为已连接
    console.log('Connected to the WebSocket server.');
  };

  ws.onerror = (error) => {
    console.error('WebSocket Error: ', error);
  };

  ws.onclose = () => {
    isConnected = false;  // 连接关闭，重置标记
    console.log('WebSocket Connection Closed.');
  };
}

connect();  // 进行初始连接

onBeforeUnmount(() => {
  ws && ws.close();
});
</script>